import time
from typing import List
import re
from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.webdriver import WebDriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.actions import interaction
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.pointer_input import PointerInput

from cash_pos.constants.common_sequence import SWITCH_ENV, DishReturnReason
from cash_pos.function.common_function import CommonFunction
from cash_pos.model.selected_good import SelectedGood
from cash_pos.model.return_goods import ReturnGoods
from cash_pos.constants.common_sequence import SWITCH_ENV
from functional import seq

"""
Description:  关于部分退菜相关的页面交互
Note:  1. 关于设定进行退菜只根据名称进行退菜（测试时不要选择一个菜品含有多个小料或规格导致不同的价格）；
"""


class PartReturnPage(object):
    """
    关于部分退菜
    """

    def __init__(self, client):
        self.client = client
        self.driver: WebDriver = client.driver

    """
    Service Function
    """


    def return_meal_from_requirement(self, good_list: List[ReturnGoods]):
        """
        根据所需进行退菜
        Params:
        -good_list:退菜列表
        """
        tv_add_element = self.driver.find_element(AppiumBy.ID, f'{SWITCH_ENV}:id/tv_add')
        from_x, from_y, to_x, to_y = CommonFunction(self.client).get_from_to_location(tv_add_element)
        target_x = int((int(from_x) + int(to_x)) // 2)
        for tag in range(4):
            unreturn_goods = seq(good_list).filter(lambda r: r.state == False).to_list()
            if len(unreturn_goods) == 0:
                break
            for return_good in good_list:
                if return_good.state is False:
                    # 这里选取的元素有两个，一个是退款界面，另一个是隐藏在之下的订单详情页面
                    target_position = self.driver.find_elements(AppiumBy.XPATH, f'//android.widget.TextView[@resource-id="{SWITCH_ENV}:id/tv_goods" and @text="{return_good.name}"]')
                    if len(target_position) > 1:
                        from_x_0, from_y_0, to_x_0, to_y_0 = CommonFunction(self.client).get_from_to_location(target_position[0])
                        from_x_1, from_y_1, to_x_1, to_y_1 = CommonFunction(self.client).get_from_to_location(target_position[1])
                        if int(from_x_0) < int(from_x_1):
                            from_x, from_y, to_x, to_y = from_x_0, from_y_0, to_x_0, to_y_0
                        else:
                            from_x, from_y, to_x, to_y = from_x_1, from_y_1, to_x_1, to_y_1
                        target_y = int((int(from_y) + int(to_y)) // 2)
                        # 点击
                        for num in range(return_good.number):
                            actions = ActionChains(self.driver)
                            actions.w3c_actions = ActionBuilder(self.driver, mouse=PointerInput(interaction.POINTER_TOUCH, "touch"))
                            # 计算X,Y值
                            actions.w3c_actions.pointer_action.move_to_location(target_x, target_y)
                            actions.w3c_actions.pointer_action.pointer_down()
                            actions.w3c_actions.pointer_action.pause(1)
                            actions.w3c_actions.pointer_action.release()
                            actions.perform()
                            time.sleep(0.5)
                        return_good.state = True
            # 进行滑动直到下一页
            element_main = self.driver.find_element(AppiumBy.XPATH,f'//*[@resource-id="{SWITCH_ENV}:id/ll_cart_list_view"]/*[@resource-id="{SWITCH_ENV}:id/recycler_view"]')
            element_location = re.match(r"\[(\d+,\d+)\]", element_main.get_attribute("bounds")).group(1).split(',')
            element_location_x, element_location_y = int(element_location[0].strip()), int(element_location[1].strip())
            element_height = element_main.size['height']
            self.driver.swipe(start_x=element_location_x + 100, start_y=element_location_y + element_height / 2, end_x=element_location_x + 100, end_y=element_location_y, duration=1000)
            return self

    """
    Button Function
    """

    def print_return_label_confirm(self):
        """
        打印退菜单
        """
        self.driver.find_element(AppiumBy.ID, f'{SWITCH_ENV}:id/cb_print_return').click()
        return self

    def print_statement_label_confirm(self):
        """
        打印结账单
        """
        self.driver.find_element(AppiumBy.ID, f'{SWITCH_ENV}:id/cb_print_samll').click()
        return self

    def confirm(self):
        """
        确认
        """
        self.driver.find_element(AppiumBy.ID, f'{SWITCH_ENV}:id/tv_submit').click()
        from cash_pos.page.order_page.order_list_page import OrderListPage
        return OrderListPage(self.client)

    def select_reason_option(self, reason: str):
        """
        选择原因选项
        reason:原因
        """
        options_elements = self.driver.find_elements(AppiumBy.ID, f'{SWITCH_ENV}:id/tvOption')
        if reason == DishReturnReason.dishproblem.value:
            options_elements[2].click()
        if reason == DishReturnReason.multiple.value:
            options_elements[0].click()
        if reason == DishReturnReason.sellout.value:
            options_elements[1].click()
        return self

    def insert_reason_option(self, reason: str):
        """
        输入理由
        reason:原因
        """
        self.driver.find_element(AppiumBy.ID, f'{SWITCH_ENV}:id/et_reason').send_keys(reason.strip())
        return self
